package com.roadmap.struts.action.admin.msg;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;

import com.roadmap.biz.common.IManager;
import com.roadmap.biz.common.ManagerFactory;
import com.roadmap.biz.message.MessageManager;
import com.roadmap.cache.RdcSessionCache;
import com.roadmap.client.sns.FriendshipManager;
import com.roadmap.common.RdcConst;
import com.roadmap.entities.Message;
import com.roadmap.entities.ext.DialogExt;
import com.roadmap.entities.ext.FriendExt;
import com.roadmap.exception.NullObjectException;
import com.roadmap.struts.action.ActionConst;
import com.roadmap.struts.action.RdcDispatchAction;
import com.roadmap.struts.form.admin.msg.MessageForm;

public class MessageAction extends RdcDispatchAction {

	@Override
	protected ActionForward doView(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String currentUser = getUIDFromSession(request);
		String entityId = request.getParameter(ActionConst.Item_Id_In_Request);
		if (entityId != null) {
			IManager mgr = ManagerFactory.getInstance(RdcConst.MESSAGE, currentUser);
			DialogExt dlg = (DialogExt) mgr.getEntityExt(entityId);
			if (dlg != null) {
				request.setAttribute("messages", dlg.getMessages());
				
				// no need to transfer the messages again
				dlg.setMessages(null);
				request.setAttribute("dialog", dlg);
			}
		}
		else {
			throw new Exception("invalid parameter");
		}

		return mapping.findForward("getmsg");
	}

	@Override
	protected ActionForward doAll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String box = request.getParameter(ActionConst.MESSAGE_BOX_FLAG);
		String currentUser = getUIDFromSession(request);
		int currentPage = getCurrentPageNum(request);
		IManager mgr = ManagerFactory.getInstance(RdcConst.MESSAGE, currentUser);
		mgr.setPage(currentPage);
		List messages = null;
		// if the box is invalid or it's not 'sent', then get inbox messages
		if (box == null || !box.equalsIgnoreCase(ActionConst.MESSAGE_BOX_SENT)) {
			messages = mgr.getExecutableEntities();
		}
		else {
			messages = mgr.getEntitiesOfOwner();
		}

		if (messages != null && !messages.isEmpty()) {
			request.setAttribute("messages", messages);

			// 更新session
			RdcSessionCache cache = (RdcSessionCache) request.getSession()
					.getAttribute(ActionConst.RDC_SESSION_CACHE_NAME);
			cache.setMessageCount(0);
			
			createPagingInfoInRequest(request, mgr);
		}
		return mapping.findForward("getmsgs");
	}

	@Override
	protected ActionForward doCreate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ownerId = getUIDFromSession(request);
		FriendshipManager mgr = new FriendshipManager(ownerId);
		// get all friends
		List friends = mgr.getFriendsByGroup("0");
		if (friends != null && !friends.isEmpty()) {
			Iterator iter = friends.iterator();
			while (iter.hasNext()) {
				FriendExt frd = (FriendExt) iter.next();
				// only transfer the friend id and name to the client
				frd.setCreatedTime(null);
				frd.setId(null);
				frd.setGroupId(null);
				frd.setUpdatedTime(null);
			}
			request.setAttribute("friends", friends);
		}

		return mapping.findForward("getmsg");
	}

	/** to save the new messages */
	@Override
	protected ActionForward doEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MessageForm msgForm = (MessageForm) form;
		String recipientString = msgForm.getRecipientIDs();
		if (recipientString == null) {
			throw new NullObjectException("param recipientString is NULL");
		}

		String[] recipients = null;
		if (recipientString.indexOf(ActionConst.PARAM_SEPARATOR) == -1) {
			recipients = new String[] { recipientString };
		}
		else {
			recipients = recipientString.split(ActionConst.PARAM_SEPARATOR);
		}
		
		String currentUser = getUIDFromSession(request);
		Message template = new Message();
		template.setContent(msgForm.getContent());
		template.setCreatedTime(msgForm.getCreatedTime());
		template.setDispatcherId(currentUser);
		template.setStatus(msgForm.getStatus());

		MessageManager mgr = (MessageManager) ManagerFactory.getInstance(RdcConst.MESSAGE, currentUser);
		mgr.create(recipients, template);
		return new ActionRedirect("/message.do?act=all&msg=sent");
	}

	@Override
	public boolean isFormSubmitted(HttpServletRequest request) throws Exception {
		return false;
	}
}
